<?php
namespace backend\controllers;

use Yii;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use backend\models\NewsFlash;
use backend\models\NewsNom;
use yii\web\Response;
use common\helpers\StringHelper;
use yii\helpers\Html;

class NewsflashController extends Controller
{
    public $enableCsrfValidation = false;

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['index', 'create', 'ueditor', 'viewbefore','viewiframe','view', 'update', 'upload','delete'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }
    public function actions(){
        return [
            'ueditor'=>[
                'class' => 'common\widgets\ueditor\UeditorAction',
                'config'=>[
                    //上传图片配置
                    'imageUrlPrefix' => "http://image.bbeats.io/", /* 图片访问路径前缀 */
                    'imagePathFormat' => "uploads/news/innner/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
                ]
            ]
        ];
    }

    public function actionIndex()
    {
        $types = array(
            'all' => NewsNom::NEWS_STATUS_ALL,
            'draft' => NewsNom::NEWS_STATUS_DRA,
            'published' => [NewsNom::NEWS_STATUS_NOM, NewsNom::NEWS_STATUS_WAT],
            'recycle' => NewsNom::NEWS_STATUS_DEL
        );
        $active = Yii::$app->request->get("active",'all');
        $active = in_array($active,array_keys($types)) ? $active : 'all';

        $buld = NewsFlash::find();
        if( $active != 'all' ) $buld = $buld->where(['status' => $types[$active]]);

        $dataProvider = new ActiveDataProvider([
            'query' => $buld->orderBy(['id' => SORT_DESC]),
            'pagination' => [
                'pageSize' => 15,
            ],
        ]);
        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'active' => $active
        ]);
    }

    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    public function actionCreate()
    {
        $model = new NewsFlash();
        $user = Yii::$app->user->identity;
        $post = Yii::$app->request->post();
        if ($model->load($post) && $model->validate()) {
            if( $model->status == NewsNom::NEWS_STATUS_WAT ){
                if( strtotime($model->ptime) <= time() ){
                    return false;
                }
            }
            $model->userid = $user->id;
            $model->username = $user->username;
            $model->ptime = $model->status == NewsNom::NEWS_STATUS_NOM ? date("Y-m-d H:i:s",time()) : $model->ptime;
            $model->ctime = time();
            $model->mtime = time();
            $model->save(false);
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            $model->ishot = 0;
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $user = Yii::$app->user->identity;
        $post = Yii::$app->request->post();

        if ($model->load($post) && $model->validate()) {
            if( $model->status == NewsNom::NEWS_STATUS_WAT ){
                if( strtotime($model->ptime) <= time() ){
                    return $this->render('update', [
                        'model' => $model,
                        'msg' => '请正确填写发布时间'
                    ]);
                }
            }
            $model->userid = $user->id;
            $model->username = $user->username;
            $model->ptime = $model->status == NewsNom::NEWS_STATUS_NOM ? date("Y-m-d H:i:s",time()) : $model->ptime;
            $model->mtime = time();
            $model->save(false);
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }
    public function actionViewiframe(){
        $this->layout = "main-single";
        //$type = Yii::$app->request->get("id");
        $type = Yii::$app->request->get("type");
        //$model = $this->findModel($id);
        return $this->render('viewiframe', ['type' => $type]);
    }
    public function actionViewbefore(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $newsid = Yii::$app->request->get("data-id");
        $type = Yii::$app->request->get("type");

        return [
            'title' => StringHelper::truncateMsg("viewbefore", 160),
            'content' => $this->renderAjax('viewbefore',['newsid' => $newsid,'type' => $type]),
            'footer' => Html::button('close', ['class' => 'btn btn-default pull-right close','data-dismiss' => "modal"]).
                Html::button('close', ['class' => 'btn btn-default pull-left close', 'data-dismiss' => "modal"])
        ];
    }

    public function actionDelete($id)
    {
        NewsFlash::updateAll(['status' => 1],['id' => $id]);
        return $this->redirect(['index']);
    }

    /**
     * 返回格式参见
     */
    public function actionUpload()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        //TODO FileUpload
    }

    protected function findModel($id)
    {
        if (($model = NewsFlash::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('您请求的页面不存在');
        }
    }
}
